import { Message } from 'element-ui';

let utils = {};

// 成功提示
utils.success = function (msg = '成功') {
    Message.success({
        message: msg,
        customClass: 'zd-el-message'
    });
};

// 成功提示
utils.error = function (msg = '失败') {
    Message.error({
        message: msg,
        customClass: 'zd-el-message'
    });
};

// 非空判断
utils.notEmpty = function (o) {
    if (o == undefined || o == '' || o == null) {
        return false;
    }
    return true;
};

// 空判断
utils.isEmpty = function (o) {
    if (o == undefined || o == '' || o == null) {
        return true;
    }
    return false;
};

utils.debounce =  function(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function(...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

utils.resetForm = function(refName) {
  if (this.$refs[refName]) {
    this.$refs[refName].resetFields();
  }
}

/** 判断数组多个对象的某一元素，是否存在相同值的情况*/
utils.isRepeat = function(arr,key) {
  if(arr.length==1) return false
  let set = new Set()     //根据Set的特性做判断
  arr.forEach(item=>{
    set.add(item[key])
  })
  return set.size === 1
}

utils.compressImg = function(file) {
  return new Promise(function(resolve, reject) {
    var fileSize = Math.ceil(parseInt(file['file']['size']) / 1024 / 1024)
    console.log(fileSize)
    // var compress = 1 / fileSize;
    var read = new FileReader()
    read.readAsDataURL(file.file)
    read.onload = function(e) {
      var img = new Image()
      img.src = e.target.result
      img.onload = function() {
        // 默认按比例压缩
        var w = this.width
        var h = this.height
        // 生成canvas
        var canvas = document.createElement('canvas')
        var ctx = canvas.getContext('2d')
        var base64
        // 创建属性节点
        canvas.setAttribute('width', w)
        canvas.setAttribute('height', h)
        ctx.drawImage(this, 0, 0, w, h)
        // base64 = canvas.toDataURL(file['file']['type'], 0.2)
        if (fileSize <= 1) {
          base64 = canvas.toDataURL(file['file']['type'], 1)
        } else if (fileSize > 1 && fileSize < 2) {
          base64 = canvas.toDataURL(file['file']['type'], 0.4)
        } else {
          base64 = canvas.toDataURL(file['file']['type'], 0.2)
        }
        // 回调函数返回file的值（将base64编码转成file）
        let binary = atob(base64.split(',')[1]);
        let mime = base64.split(',')[0].match(/:(.*?);/)[1];
        let array = [];
        for (let i = 0; i < binary.length; i++) {
          array.push(binary.charCodeAt(i));
        }
        let fileData = new Blob([new Uint8Array(array)], {
          type: mime,
        })
        let newFile = new File([fileData], file.file.name, { type: mime });
        resolve(newFile)
      }
    }
  })
},

/** 深克隆*/
utils.deepClone = function(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = utils.deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}



utils.isExternal = function (path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}


export default utils;
